package com.itheima.exception;

import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.ServletException;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class MyHandlerException {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RuntimeException.class)
    public Result handlerRuntimeException(RuntimeException e){
        log.debug("error：" +e );
        if(e instanceof AccessDeniedException){
            return new Result(false, "认证失败或者权限不足，请重新登录！！");
        }
        String message = e.getMessage();
        return new Result(false,message);
    }


    @ExceptionHandler({
            ServletException.class,                     // mediaType不匹配、method不匹配……
            HttpMessageConversionException.class,       //http body转换异常，@RequestBody的参数
            MethodArgumentNotValidException.class ,     //http请求缺少查询参数
            MethodArgumentTypeMismatchException.class   //http请求参数类型不匹配
    })
    public Result handlerOtherException(Exception e) throws Exception {
        System.out.println("出错了");
        throw e;
    }


    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({
            Exception.class
    })
    public Result handlerException(Exception e) {
        log.debug("error：" +e );
        return new Result(false, MessageConst.ACTION_FAIL);
    }
}
